import "./css/flatpickr.min.css"
import "./css/mobile.css"
import "./js/flatpickr.min.js"
import "./js/flatpickr.zh.js"
import { 排盘 } from '../src/bazi.ts';

document.addEventListener('DOMContentLoaded', function() {
    // 初始化日期时间选择器
    const datePicker = flatpickr("#datePicker", {
        locale: "zh",
        dateFormat: "Y-m-d",
        defaultDate: "2025-01-01",
        onChange: function(selectedDates, dateStr, instance) {
            const date = selectedDates[0];
            document.getElementById('year').value = date.getFullYear();
            document.getElementById('month').value = date.getMonth() + 1;
            document.getElementById('day').value = date.getDate();
        }
    });
    
    const timePicker = flatpickr("#timePicker", {
        locale: "zh",
        enableTime: true,
        noCalendar: true,
        dateFormat: "H:i",
        time_24hr: true,
        defaultDate: "12:00",
        onChange: function(selectedDates, dateStr, instance) {
            const date = selectedDates[0];
            document.getElementById('hour').value = date.getHours();
            document.getElementById('minute').value = date.getMinutes();
        }
    });
    
    // 设置初始值
    const initialDate = new Date();
    document.getElementById('year').value = initialDate.getFullYear();
    document.getElementById('month').value = initialDate.getMonth() + 1;
    document.getElementById('day').value = initialDate.getDate();
    // document.getElementById('hour').value = initialDate.getHours();
    // document.getElementById('minute').value = initialDate.getMinutes();
    
    const calculateBtn = document.getElementById('calculateBtn');
    const loadingSpinner = document.getElementById('loadingSpinner');
    const buttonText = document.getElementById('buttonText');
    const errorMessage = document.getElementById('errorMessage');
    const copyTextButton = document.getElementById('copyTextButton');

    copyTextButton.addEventListener('click', function() {
        const resultText = document.getElementById('resultText').textContent;
        navigator.clipboard.writeText(resultText).then(function() {
            alert('文本已复制到剪贴板');
        }, function(err) {
            alert('复制失败: ', err);
        });
    });

    calculateBtn.addEventListener('click', function() {
        // 获取输入值
        const calendarType = document.querySelector('input[name="calendarType"]:checked').value;
        const year = parseInt(document.getElementById('year').value);
        const month = parseInt(document.getElementById('month').value);
        const day = parseInt(document.getElementById('day').value);
        const hour = parseInt(document.getElementById('hour').value);
        const minute = parseInt(document.getElementById('minute').value) || 0;
        const second = parseInt(document.getElementById('second').value) || 0;
        const gender = document.querySelector('input[name="gender"]:checked').value;
        const sect = parseInt(document.querySelector('input[name="sect"]:checked').value);
        const showXiaoyun = document.querySelector('input[name="showXiaoyun"]:checked').value === 'true';
        const showYear = document.querySelector('input[name="showYear"]:checked').value === 'true';
        
        // 验证输入
        if (!year || !month || !day || hour === undefined) {
            showError('请填写完整的生辰信息！');
            return;
        }
        
        // 隐藏错误信息，显示加载状态
        hideError();
        setLoadingState(true);
        
        console.log(`开始排盘: 性别${gender}；${year}-${month}-${day} ${hour}:${minute}:${second}`);
        // 模拟API调用，实际应用中替换为真实的排盘函数
        setTimeout(() => {
            try {
                // 这里应该是真实的排盘函数调用
                const result = 排盘(gender, {类型: calendarType, 年: year, 月: month, 日: day, 时: hour, 分: minute, 秒: second}, showXiaoyun, showYear, sect);
                
                // 模拟结果数据，根据提供的返回数据结构
                // const result = generateMockResult(year, month, day, hour, minute, gender, showXiaoyun, showYear);
                
                // 显示结果
                displayResult(result);
                setLoadingState(false);
            } catch (error) {
                console.error('排盘错误:', error);
                showError('排盘过程中出现错误，请检查输入数据是否正确。');
                setLoadingState(false);
            }
        }, 0); // 模拟网络延迟
    });

    function setLoadingState(isLoading) {
        if (isLoading) {
            calculateBtn.disabled = true;
            loadingSpinner.style.display = 'inline-block';
            buttonText.textContent = '排盘中...';
        } else {
            calculateBtn.disabled = false;
            loadingSpinner.style.display = 'none';
            buttonText.textContent = '开始排盘';
        }
    }
    
    function showError(message) {
        errorMessage.textContent = message;
        errorMessage.style.display = 'block';
    }
    
    function hideError() {
        errorMessage.style.display = 'none';
    }
    
    function displayResult(result) {
        // 更新四柱八字
        document.getElementById('yearPillar').textContent = result.年柱.干支;
        document.getElementById('monthPillar').textContent = result.月柱.干支;
        document.getElementById('dayPillar').textContent = result.日柱.干支;
        document.getElementById('hourPillar').textContent = result.时柱.干支;
        
        // 更新四柱详情
        document.getElementById('yearDetail').textContent = `${result.年柱.天干}${result.年柱.地支} ${result.年柱.天干阴阳}${result.年柱.地支阴阳}`;
        document.getElementById('monthDetail').textContent = `${result.月柱.天干}${result.月柱.地支} ${result.月柱.天干阴阳}${result.月柱.地支阴阳}`;
        document.getElementById('dayDetail').textContent = `${result.日柱.天干}${result.日柱.地支} ${result.日柱.天干阴阳}${result.日柱.地支阴阳}`;
        document.getElementById('hourDetail').textContent = `${result.时柱.天干}${result.时柱.地支} ${result.时柱.天干阴阳}${result.时柱.地支阴阳}`;
        
        // 更新五行
        document.getElementById('yearWuxing').textContent = result.年柱.天干五行 + result.年柱.地支五行;
        document.getElementById('monthWuxing').textContent = result.月柱.天干五行 + result.月柱.地支五行;
        document.getElementById('dayWuxing').textContent = result.日柱.天干五行 + result.日柱.地支五行;
        document.getElementById('hourWuxing').textContent = result.时柱.天干五行 + result.时柱.地支五行;
        
        // 更新命主
        document.getElementById('mingzhu').textContent = `${result.日柱.天干}${result.日柱.天干五行}日主`;
        
        // 更新起运信息
        document.getElementById('qiyunInfo').textContent = result.起运;
        
        // 更新大运列表
        const dayunList = document.getElementById('dayunList');
        dayunList.innerHTML = '';
        result.大运列表.forEach(dayun => {
            const item = document.createElement('div');
            item.className = 'list-item';
            item.innerHTML = `
                <span>${dayun.开始年龄}-${dayun.结束年龄}岁 (${dayun.开始年份}-${dayun.结束年份})</span>
                <span>${dayun.干支}</span>
            `;
            const detail = document.createElement('div');
            detail.className = 'list-detail';
            detail.textContent = `旬: ${dayun.旬} | 旬空: ${dayun.旬空}`;
            item.appendChild(detail);
            dayunList.appendChild(item);
        });
        
        // 更新流年列表
        const liunianList = document.getElementById('liunianList');
        liunianList.innerHTML = '';
        if (result.流年列表 && result.流年列表.length > 0) {
            result.流年列表.forEach(liunian => {
                const item = document.createElement('div');
                item.className = 'list-item';
                item.innerHTML = `
                    <span>${liunian.年份}年 (${liunian.年龄}岁)</span>
                    <span>${liunian.干支}</span>
                `;
                const detail = document.createElement('div');
                detail.className = 'list-detail';
                detail.textContent = `旬: ${liunian.旬} | 旬空: ${liunian.旬空}`;
                item.appendChild(detail);
                liunianList.appendChild(item);
            });
        } else {
            liunianList.innerHTML = '<div class="list-item">未显示流年信息</div>';
        }
        
        // 更新命理分析文本
        document.getElementById('resultText').textContent = result.文本;
    }
});